package com.huishu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huishu.commons.exception.BaseException;
import com.huishu.commons.exception.NotFoundException;
import com.huishu.commons.pojo.BasePage;
import com.huishu.commons.pojo.Result;
import com.huishu.commons.utlis.BeanUtils;
import com.huishu.commons.utlis.WechatUtil;
import com.huishu.user.mapper.ActivityPageMapper;
import com.huishu.user.pojo.dto.ActivityPageCreateDTO;
import com.huishu.user.pojo.dto.ActivityPageUpdateDTO;
import com.huishu.user.pojo.dto.PageDataDTO;
import com.huishu.user.pojo.model.ActivityHomePageDO;
import com.huishu.user.pojo.model.ActivityPageDO;
import com.huishu.user.pojo.model.HomeImageUrlDO;
import com.huishu.user.pojo.model.HomePageDO;
import com.huishu.user.pojo.vo.ActivityPageVO;
import com.huishu.user.pojo.vo.PageDataVO;
import com.huishu.user.service.ActivityHomePageService;
import com.huishu.user.service.ActivityPageService;
import com.huishu.user.service.HomeImageUrlService;
import com.huishu.user.service.HomePageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator@ljj
 * @since 2023-06-19
 */
@Slf4j
@Service
public class ActivityPageServiceImpl extends ServiceImpl<ActivityPageMapper, ActivityPageDO> implements ActivityPageService {

    private static final String URL_VALUE = "pagesA/activity/activity?id=";

    @Autowired
    private HomeImageUrlService homeImageUrlService;

    @Autowired
    private HomePageService homePageService;

    @Autowired
    private ActivityHomePageService activityHomePageService;

    @Override
    public Result pageList(BasePage basePage) {
        Page<ActivityPageDO> page = new Page<>(basePage.getCurrPage(), basePage.getPageSize());
        LambdaQueryWrapper<ActivityPageDO> queryWrapper = Wrappers.lambdaQuery(ActivityPageDO.class)
                .like(StringUtils.isNotBlank(basePage.getSearch()), ActivityPageDO::getName, basePage.getSearch())
                .orderByDesc(ActivityPageDO::getCreatedDate);
        return Result.success(this.baseMapper.selectPage(page, queryWrapper));
    }

    @Transactional
    @Override
    public Result create(ActivityPageCreateDTO activityPageCreateDTO) {
        ActivityPageDO activityPageDO = BeanUtils.copyProperties(activityPageCreateDTO, ActivityPageDO.class);
        boolean save = this.save(activityPageDO);
        if (!save) {
            throw new BaseException("新增失败！");
        }
        bindActivityHmoePage(activityPageCreateDTO.getPageDatas(), activityPageDO.getId());
        LambdaUpdateWrapper<ActivityPageDO> uw = Wrappers.lambdaUpdate(ActivityPageDO.class)
                .set(ActivityPageDO::getUrl, URL_VALUE + activityPageDO.getId())
                .eq(ActivityPageDO::getId, activityPageDO.getId());
        this.update(uw);
        return Result.success();
    }

    @Override
    public Result modify(ActivityPageUpdateDTO activityPageUpdateDTO) {
        ActivityPageDO activityPageDO = BeanUtils.copyProperties(activityPageUpdateDTO, ActivityPageDO.class);
        boolean save = this.updateById(activityPageDO);
        if (!save) {
            throw new BaseException("新增失败！");
        }
        LambdaQueryWrapper<ActivityHomePageDO> queryWrapper = Wrappers.lambdaQuery(ActivityHomePageDO.class)
                .eq(ActivityHomePageDO::getActivityPageId, activityPageDO.getId());
        List<ActivityHomePageDO> ActivityHomePages = activityHomePageService.list(queryWrapper);
        List<Long> homePageIds = ActivityHomePages.stream().map(ActivityHomePageDO::getHomePageId).collect(Collectors.toList());
        boolean b = homePageService.removeByIds(homePageIds);
        if (!b) {
            throw new BaseException("修改失败 : homePageService.removeByIds");
        }
        LambdaQueryWrapper<HomeImageUrlDO> queryWrapperHomeImageUrl = Wrappers.lambdaQuery(HomeImageUrlDO.class)
                .in(HomeImageUrlDO::getHomePageId, homePageIds);
        boolean b1 = homeImageUrlService.remove(queryWrapperHomeImageUrl);
        if (!b1) {
            throw new BaseException("修改失败 : homeImageUrlService.remove");
        }
        boolean b2 = activityHomePageService.remove(queryWrapper);
        if (!b2) {
            throw new BaseException("修改失败 : activityHomePageService.remove");
        }
        bindActivityHmoePage(activityPageUpdateDTO.getPageDatas(), activityPageDO.getId());
        return Result.success();
    }


    @Override
    public Result disableOrOpen(ActivityPageUpdateDTO activityPageUpdateDTO) {
        LambdaUpdateWrapper<ActivityPageDO> uw = Wrappers.lambdaUpdate(ActivityPageDO.class)
                .set(ActivityPageDO::getIsRelease, activityPageUpdateDTO.getIsRelease())
                .eq(ActivityPageDO::getId, activityPageUpdateDTO.getId());
        return this.update(uw) ? Result.success() : Result.fail();
    }

    @Override
    public Result findById(Long id) {
        ActivityPageDO activityPageDO = getById(id);
        if (activityPageDO == null || !activityPageDO.getIsRelease()) {
            return Result.fail("页面已下架");
        }
        ActivityPageVO activityPageVO = BeanUtils.copyProperties(activityPageDO, ActivityPageVO.class);
        LambdaQueryWrapper<ActivityHomePageDO> queryWrapper = Wrappers.lambdaQuery(ActivityHomePageDO.class)
                .eq(ActivityHomePageDO::getActivityPageId, activityPageDO.getId());
        List<ActivityHomePageDO> ActivityHomePages = activityHomePageService.list(queryWrapper);
        List<Long> homePageIds = ActivityHomePages.stream().map(ActivityHomePageDO::getHomePageId).collect(Collectors.toList());
        LambdaQueryWrapper<HomePageDO> queryWrapperHomePage = Wrappers.lambdaQuery(HomePageDO.class)
                .in(HomePageDO::getId, homePageIds);
        List<HomePageDO> homePages = homePageService.list(queryWrapperHomePage);
        if (CollectionUtils.isEmpty(homePageIds)) {
            throw new NotFoundException("无配置数据");
        }
        // 查询图片和url
        LambdaQueryWrapper<HomeImageUrlDO> queryWrapperHomeImageUrl = Wrappers.lambdaQuery(HomeImageUrlDO.class)
                .in(HomeImageUrlDO::getHomePageId, homePageIds)
                .orderByAsc(HomeImageUrlDO::getSort);
        List<HomeImageUrlDO> homeImageUrlDOS = homeImageUrlService.list(queryWrapperHomeImageUrl);
        Map<Long, List<HomeImageUrlDO>> homeImageUrlMap = homeImageUrlDOS.stream().collect(Collectors.groupingBy(HomeImageUrlDO::getHomePageId));
        List<PageDataVO> collect = homePages.stream().map(homePageDO -> {
            PageDataVO pageDataVO = BeanUtils.copyProperties(homePageDO, PageDataVO.class);
            pageDataVO.setHomeImageUrl(homeImageUrlMap.get(homePageDO.getId()));
            return pageDataVO;
        }).collect(Collectors.toList());
        activityPageVO.setPageDatas(collect);
        return Result.success(activityPageVO);
    }

    @Transactional
    @Override
    public Result delete(Long id) {
        LambdaQueryWrapper<ActivityHomePageDO> queryWrapper = Wrappers.lambdaQuery(ActivityHomePageDO.class)
                .eq(ActivityHomePageDO::getActivityPageId, id);
        List<ActivityHomePageDO> activityHomePages = activityHomePageService.list(queryWrapper);
        activityHomePageService.remove(queryWrapper);
        List<Long> homePageIds = activityHomePages.stream().map(ActivityHomePageDO::getHomePageId).collect(Collectors.toList());
        homePageService.removeByIds(homePageIds);
        LambdaQueryWrapper<HomeImageUrlDO> queryWrapper1 = Wrappers.lambdaQuery(HomeImageUrlDO.class)
                .in(HomeImageUrlDO::getHomePageId, homePageIds);
        homeImageUrlService.remove(queryWrapper1);
        this.removeById(id);
        return Result.success();
    }

    @Override
    public Result<String> generateQrCode(Long id) {
        ActivityPageDO activityPageDO = this.getById(id);
        String url = activityPageDO.getUrl();
        try {
            String params = url.substring(url.indexOf("?"), url.length());
            String urlStr = url.substring(0, url.indexOf("?"));
            String value = WechatUtil.generateQrCode(params, urlStr);
            return Result.success(value);
        } catch (Exception e) {
            log.error("获取小程序码失败", e);
            return Result.fail("获取小程序码失败");
        }
    }

    /**
     * 维护页面数据
     *
     * @param pageDatas
     * @param ActivityPageId
     */
    private void bindActivityHmoePage(List<PageDataDTO> pageDatas, Long ActivityPageId) {
        List<ActivityHomePageDO> activityHomePages = new ArrayList<>();
        for (PageDataDTO pageData : pageDatas) {
            HomePageDO homePageDO = BeanUtils.copyProperties(pageData, HomePageDO.class);
            if (!homePageService.save(homePageDO)) {
                throw new BaseException("新增页面内容失败!");
            }
            List<HomeImageUrlDO> collect = pageData.getHomeImageUrl().stream().map(homeImageUrlDO -> homeImageUrlDO.setHomePageId(homePageDO.getId())).collect(Collectors.toList());
            boolean b = homeImageUrlService.saveBatch(collect);
            if (!b) {
                throw new BaseException("新增页面内容失败");
            }
            // 新增活动和页面关系
            ActivityHomePageDO activityHomePageDO = new ActivityHomePageDO();
            activityHomePageDO.setActivityPageId(ActivityPageId);
            activityHomePageDO.setHomePageId(homePageDO.getId());
            activityHomePages.add(activityHomePageDO);
        }
        boolean b = activityHomePageService.saveBatch(activityHomePages);
        if (!b) {
            throw new BaseException("新增页面活动关系失败");
        }
    }
}
